package com.xiaoyi.springboot.shiro;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xiaoyi.springboot.constant.Constants;
import com.xiaoyi.springboot.enums.UserType;
import com.xiaoyi.springboot.exception.CommonException;
import com.xiaoyi.springboot.util.SpringContextUtils;
import com.xiaoyi.springboot.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * @Author Scott
 * @Date 2018-07-12 14:23
 * @Desc JWT工具类
 **/
public class JwtUtil {

	// Token过期时间30分钟（用户登录过期时间是此时间的两倍，以token在reids缓存时间为准）
	public static final long EXPIRE_TIME = 30 * 60 * 1000;
	//token私钥
	private static final String TOKEN_SECRET = "abcdefg";
	
	private static final String USER_NAME = "userName";
	private static final String USER_TYPE = "userType";
	
	/**
	 * 校验token是否正确
	 *
	 * @param token  密钥
	 * @param secret 用户的密码
	 * @return 是否正确
	 */
	public static boolean verify(String token, String username, String secret) {
		try {
			// 根据密码生成JWT效验器
			Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
			JWTVerifier verifier = JWT.require(algorithm).withClaim(USER_NAME, username).build();
			// 效验TOKEN
			DecodedJWT jwt = verifier.verify(token);
			return true;
		} catch (Exception exception) {
			return false;
		}
	}

	/**
	 * 获得token中的信息无需secret解密也能获得
	 *
	 * @return token中包含的用户名
	 */
	public static String getUsername(String token) {
		try {
			DecodedJWT jwt = JWT.decode(token);
			return jwt.getClaim(USER_NAME).asString();
		} catch (JWTDecodeException e) {
			return null;
		}
	}

	/**
	 * 生成签名,5min后过期
	 *
	 * @param username 用户名
	 * @param secret   用户的密码
	 * @return 加密的token
	 */
	public static String sign(String username, String secret) throws UnsupportedEncodingException {
		Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
		Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
		// 附带username信息
		return JWT.create().withClaim(USER_NAME, username).withExpiresAt(date).sign(algorithm);

	}

	/**
	 * 生成签名,5min后过期
	 *
	 * @param username 用户名
	 * @param secret   用户的密码
	 * @return 加密的token
	 */
	public static String sign(String username, String secret, String userType) throws UnsupportedEncodingException {
		Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
		Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
		// 附带username信息

		return JWT.create()
				.withClaim(USER_NAME, username)
				.withClaim(USER_TYPE, userType)
				.withExpiresAt(date)
				.sign(algorithm);
	}


	/**
	 * 根据request中的token获取用户账号
	 * 
	 * @param request
	 * @return
	 * @throws CommonException
	 */
	public static String getUserNameByToken(HttpServletRequest request) throws CommonException {
		String accessToken = request.getHeader(Constants.X_ACCESS_TOKEN);
		String username = getUsername(accessToken);
		if (StringUtils.isEmpty(username)) {
			throw new CommonException("未获取到用户");
		}
		return username;
	}
	/**
	 * 根据request中的token获取用户账号
	 *
	 * @return
	 * @throws CommonException
	 */
	public static String getUserNameByToken() throws CommonException {
		// 获取RequestAttribute
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		// 从获取的RequestAttributes中获取HttpServletRequest的信息
		HttpServletRequest request = requestAttributes.getRequest();
		String accessToken = request.getHeader(Constants.X_ACCESS_TOKEN);
		String username = getUsername(accessToken);
		if (StringUtils.isEmpty(username)) {
			throw new CommonException("未获取到用户");
		}
		return username;
	}
	/**
	  *  从session中获取变量
	 * @param key
	 * @return
	 */
	public static String getSessionData(String key) {
		//${myVar}%
		//得到${} 后面的值
		String moshi = "";
		if(key.indexOf("}")!=-1){
			 moshi = key.substring(key.indexOf("}")+1);
		}
		String returnValue = null;
		if (key.contains("#{")) {
			key = key.substring(2,key.indexOf("}"));
		}
		if (StringUtils.isNotEmpty(key)) {
			HttpSession session = SpringContextUtils.getHttpServletRequest().getSession();
			returnValue = (String) session.getAttribute(key);
		}
		//结果加上${} 后面的值
		if(returnValue!=null){returnValue = returnValue + moshi;}
		return returnValue;
	}
	/**
	 * 解析jwt
	 * @param token
	 * @return
	 */
	public static JwtToken  parseJWT(String token){
		if (StringUtils.isEmpty(token)){
			return  new JwtToken();
		}
		Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
		JWTVerifier jwtVerifier = JWT.require(algorithm).build();
		DecodedJWT decodedJWT = jwtVerifier.verify(token);
		String userName = decodedJWT.getClaim(USER_NAME).asString();
		String userType = decodedJWT.getClaim(USER_TYPE).asString();
		if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(userType)){
			return  new JwtToken();
		}
		return new JwtToken(token,userType);

	}

	
	public static void main(String[] args) {
		 /*String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NjUzMzY1MTMsInVzZXJuYW1lIjoiYWRtaW4ifQ.xjhud_tWCNYBOg_aRlMgOdlZoWFFKB_givNElHNw3X0";
		 System.out.println(JwtUtil.getUsername(token));
		 */
		System.out.println(parseJWT("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyVHlwZSI6ImFkbWludXNlciIsImV4cCI6MTYzMzc5NzY1NCwidXNlcm5hbWUiOiJ4aWFveWkifQ.LLOqmB56XrUyjJOVZpR3dVHIPnZeYJ62j-Wn2XndOI0"));


	}

	public static String getUserType(String token) {
		try {
			DecodedJWT jwt = JWT.decode(token);
			return jwt.getClaim(USER_TYPE).asString();
		} catch (JWTDecodeException e) {
			return null;
		}

	}
}
